import * as Koa from 'koa';
import { Transaction } from 'tiny-entity2';
import { route, RouteOptionsVerify, ServiceManager, UsingLock } from "../../common";
import { ServiceException } from '../../common/excpetion';
import { ApiDataContext } from '../../domain/apiDataContext';
import { Department } from '../../domain/models/department';
import { OrganizationTree } from '../../domain/models/organizationTree';
import { checkIsChildDep, OrganizationTreeService } from '../../service/OrganizationTreeService';
const orzTreeSvr = ServiceManager.Current.GetService<OrganizationTreeService>('OrganizationTreeService');

class OrganizationTreeController {
    @route(new RouteOptionsVerify('GET', '/api/organizationTree'))
    async queryOrganizationTrees(ctx: Koa.Context, next) {
        let rootOrgId = ctx.headers['orgid'];
        let params = ctx.query;
        if (!rootOrgId) rootOrgId = "";
        params.organizationId = rootOrgId;

        let data = await orzTreeSvr.QueryOrganizationTree(params);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('GET', '/api/organizationTree/:id'))
    async getOrganizationTreeInfoById(ctx: Koa.Context, next) {
        let rootOrgId = ctx.headers['orgid'];
        let id = ctx.params.id;
        let data = await orzTreeSvr.GetOrganizationTreeById(id);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('PUT', '/api/organizationTree'))
    async updateorganizationTree(ctx: Koa.Context, next) {
        let rootOrgId = ctx.headers['orgid'];
        let orgtrees: OrganizationTree[] = ctx.request.body;
        let resultNodes: OrganizationTree[] = [];
        let nodeidobj=orgtrees.find(x=>x.id==null ||x.id==undefined || x.id=="");
        if(nodeidobj)
        {
            throw new ServiceException('节点Id不能为空');
        }
        ctx.response.body = await UsingLock(rootOrgId, async () => {
            return await Transaction(new ApiDataContext(), async datactx => {
                orgtrees.forEach(async x=> {
                    let currTreeNode = await orzTreeSvr.GetOrganizationTreeById(x.id);

                    if(currTreeNode.objectName==Department.name){
                        //判断当前修改的上级部门，是否为其子部门
                        let orgAllTreeData = await orzTreeSvr.QueryOrganizationTree({ "organizationId": rootOrgId,objectName:currTreeNode.objectName });
                        let dgresult:boolean=false;
                        let currparentId=currTreeNode.parentId;
                        checkIsChildDep(orgAllTreeData, currTreeNode.id, x.parentId,function(b){
                            dgresult=b;
                        });
                        if (dgresult)
                        {
                            //将所有子节点，接到上级
                            orgAllTreeData.forEach(async y=> {
                                if (y.parentId == currTreeNode.id) {
                                    y.parentId=currparentId;
                                    await orzTreeSvr.UpdateorganizationTree(y, datactx);
                                }
                            });
                        }
                    }

                    currTreeNode.parentId=x.parentId;
                    let result = await orzTreeSvr.UpdateorganizationTree(currTreeNode, datactx);
                    resultNodes.push(result);
                    return resultNodes;
                });
            });
        })

        await next();
    }
}